// 请求封装
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import i18n from '@/i18n/index'

const Router = useRouter()

export const BASE_URL = __NODE_ENV__.USE_PROXY ? '' : __NODE_ENV__.API

axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 60000

// request拦截器
axios.interceptors.request.use((config: any) => {
  config.headers.Authorization = sessionStorage.getItem('TOKEN') || ''
  return config
}, (err: any) => {
  return Promise.reject(err)
})

// responese拦截器
axios.interceptors.response.use((res: any) => {
  switch (res.data.code) {
    case 0: // 成功
      return res
    case 102: // 登录失效
      ElMessage.error(i18n.global.t('message.Login is invalid. Please log in again'))
      Router.replace('/login');
      return Promise.reject(res);
    default:
      ElMessage.error(res.data.message)
      return Promise.reject(res);
  }
}, (err: any) => {
  // 提示错误类型
  if (err.toString().indexOf('Network Error') !== -1) {
    ElMessage.error('Network Error')
  } else if (err.response > 500 && err.response.status) {
    ElMessage.error(i18n.global.t('message.Server Exception'))
  } else if (err.response && err.response.status === 404) {
    ElMessage.error(i18n.global.t('message.Request address error'))
  } else if (err.message && err.message.indexOf('timeout') !== -1) {
    ElMessage.error(i18n.global.t('message.The request timeout'))
  } else {
    ElMessage.error(error.toString());
  }
  return Promise.reject(err)
})

// 1 请求
// 1.1 post
export function post(proxy: string, url: string = '', params: object | null = null, headers: object = { versions: 'V1' }) {
  return new Promise((resolve, reject) => {
    // config.headers.version = 'V1'
    axios.request({
      url: url,
      method: 'post',
      baseURL: proxy,
      data: params,
      // headers: headers
    }).then(res => {
      resolve(res.data)
    }).catch((err) => {
      reject(err)
    })
  })
}

// 1.2 get
